package com.zzyq.pc.web.configure.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zzyq.pc.common.StandardDataFormat;
import com.zzyq.pc.common.base.BaseController;
import com.zzyq.pc.common.plugin.db.PageView;
import com.zzyq.pc.utils.HttpUtils;
import com.zzyq.pc.utils.LoggerUtils;
import com.zzyq.pc.utils.StringUtil;
import com.zzyq.pc.web.configure.model.Information;
import com.zzyq.pc.web.configure.service.IInformationService;

@Controller
@RequestMapping(value = "/information/", produces = "application/json;charset=UTF-8")
public class InformationController extends BaseController {

	@Autowired
	private IInformationService informationService;

	/**
	 * 分页查询方案列表
	 * 
	 * @param httpRequest
	 * @param response
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping("selectInformationByCompanyId")
	public String selectInformationByCompanyId(HttpServletRequest httpRequest, HttpServletResponse response,
			Integer pageIndex, Integer pageSize) {
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		PageView pageView = null;
		try {
			// 初始值
			if (pageIndex == null || pageIndex <= 0) {
				pageIndex = 1;
			}
			if (pageSize == null || pageSize <= 0) {
				pageSize = 10;
			}
			pageView = new PageView(pageSize, pageIndex);
			List<Information> informations = informationService.selectInformationByCompanyId(pageView);
			format.setTotalPages(pageView.getPageCount());
			format.setTotalRecords(pageView.getRowCount());
			return HttpUtils.formatData(format, CODE_OK, MSG_OK, informations);
		} catch (Exception e) {
			e.printStackTrace();
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
	}

	/**
	 * 新增或修改
	 * 
	 * @param httpRequest
	 * @param response
	 * @param information
	 *            方案对象
	 * @param type
	 *            1新增 2修改
	 * @return
	 */
	@ResponseBody
	@RequestMapping("insertOrUpdate")
	public String insertOrUpdate(HttpServletRequest httpRequest, HttpServletResponse response, Information information,
			Integer type) {
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		Date date = new Date();
		try {
			if (StringUtils.isBlank(information.getIfmName().trim())) {
				return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_ERROR_PARAMS, null);
			}
			if (null == type) {
				return HttpUtils.formatData(format, CODE_ERROR, "type不能为null", null);
			}
			// 同名验证
			if (informationService.selectInformationNameCountByCompanyId(information.getIfmName(),
					information.getIfmId())) {
				return HttpUtils.formatData(format, CODE_ERROR, MSG_ERROR_REPEAT, null);
			}
			// 中文转码
			information.setIfmName(transString(httpRequest, information.getIfmName()));
			information.setIfmNote(transString(httpRequest, information.getIfmNote()));
			information.setIfmType(transString(httpRequest, information.getIfmType()));
			information.setIfmGetchannel(transString(httpRequest, information.getIfmGetchannel()));
			information.setIfmNotchannel(transString(httpRequest, information.getIfmNotchannel()));
			information.setIfmGetwechatid(transString(httpRequest, information.getIfmGetwechatid()));
			information.setIfmNotwechatid(transString(httpRequest, information.getIfmNotwechatid()));
			information.setIfmGetbloggerid(transString(httpRequest, information.getIfmGetbloggerid()));
			information.setIfmNotbloggerid(transString(httpRequest, information.getIfmNotbloggerid()));
			information.setIfmGetbbsname(transString(httpRequest, information.getIfmGetbbsname()));
			information.setIfmNotbbsname(transString(httpRequest, information.getIfmNotbbsname()));
			information.setIfmGetkeyword(transString(httpRequest, information.getIfmGetkeyword()));
			information.setIfmNotkeyword(transString(httpRequest, information.getIfmNotkeyword()));
			// 参数过滤
			information = informationService.InformationFilter(information);
			// 判断关键词是否为空
			if (StringUtils.isNotBlank(information.getIfmGetkeyword())
					|| StringUtils.isNotBlank(information.getIfmNotkeyword())) {
				// 正则验证，由数字，字母,中文,+,|,()符号等
				String pattern = "^[\u4e00-\u9fa5_a-zA-Z0-9+|()\\s\\\\]+$";
				Pattern p = Pattern.compile(pattern);
				String str = information.getIfmGetkeyword();
				String str2 = information.getIfmNotkeyword();
				// 中文括号替换成英文括号
				str = str.replaceAll("（", "(").replaceAll("）", ")");
				str2 = str2.replaceAll("（", "(").replaceAll("）", ")");
				Matcher m = p.matcher(str);
				Matcher m1 = p.matcher(str2);
				if (!m.matches()) {
					return HttpUtils.formatData(format, CODE_ERROR, "匹配关键词含有非法字符", null);
				} else if (!m1.matches()) {
					return HttpUtils.formatData(format, CODE_ERROR, "过滤关键词含有非法字符", null);
				}
			}
			if (StringUtils.isNoneBlank(information.getIfmGetkeyword())) {
				char[] ifm_getKeyword = information.getIfmGetkeyword().toCharArray();
				if (!StringUtil.isBracke(ifm_getKeyword)) {
					return HttpUtils.formatData(format, CODE_ERROR, "请检查匹配关键词中括号是否完整！", null);
				}
			}
			if (StringUtils.isNoneBlank(information.getIfmNotkeyword())) {
				char[] ifm_notKeyword = information.getIfmNotkeyword().toCharArray();
				if (!StringUtil.isBracke(ifm_notKeyword)) {
					return HttpUtils.formatData(format, CODE_ERROR, "请检查过滤关键词中括号是否完整！", null);
				}
			}
			if (type == 1) {
				// 新增
				if (information.getIfmIssensitivity() == null) {
					// 默认非敏感
					information.setIfmIssensitivity(0);
				}
				// 设置is_delete = 0 关闭状态
				information.setIfmIsdelete(0);
				information.setCreateTime(date);
				information.setUpdateTime(date);
				informationService.insert(information);
			} else if (type == 2) {
				// 修改
				information.setUpdateTime(date);
				if (information.getIfmId() == null) {
					return HttpUtils.formatData(format, CODE_EXCEPTION, "请检查要修改的方案ID不能为NULL", null);
				}
				// if (information.getCreateTime() == null) {
				// return HttpUtils.formatData(format, CODE_EXCEPTION,
				// "请检查要修改的方案CreateTime字段不能为NULL", null);
				// }
				informationService.updateByPrimaryKey(information);
			}
			return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
		} catch (Exception e) {
			e.printStackTrace();
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
	}

	/**
	 * 删除方案
	 * 
	 * @param httpRequest
	 * @param response
	 * @param ifmId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("deleteByPrimaryKey")
	public String deleteByPrimaryKey(HttpServletRequest httpRequest, HttpServletResponse response, Integer ifmId) {
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		try {
			informationService.deleteByPrimaryKey(ifmId);
			return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
		} catch (Exception e) {
			e.printStackTrace();
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
	}

	/**
	 * 方案开启关闭
	 * 
	 * @param httpRequest
	 * @param response
	 * @param ifmId
	 * @param ifmIsdelete
	 * @return
	 */
	@ResponseBody
	@RequestMapping("updateInformationType")
	public String updateInformationType(HttpServletRequest httpRequest, HttpServletResponse response, Integer ifmId,
			Integer ifmIsdelete) {
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, null);
		try {
			if (null == ifmId) {
				return HttpUtils.formatData(format, CODE_ERROR, "请求的ifmId参数异常", null);
			}
			if (null == ifmIsdelete) {
				return HttpUtils.formatData(format, CODE_ERROR, "请求的ifmIsdelete参数异常", null);
			}
			informationService.updateInformationType(ifmId, ifmIsdelete);
			return HttpUtils.formatData(format, CODE_OK, MSG_OK, null);
		} catch (Exception e) {
			e.printStackTrace();
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
	}
	
	/**
	 * 根据团体ID查询所有的方案
	 * 
	 * @param httpRequest
	 * @param response
	 *            DXF写
	 */
	@ResponseBody
	@RequestMapping("selectBycompanyId")
	public String selectBycompanyId(HttpServletRequest httpRequest, HttpServletResponse response){
		List<Information> list = new ArrayList<Information>();
		StandardDataFormat format = new StandardDataFormat(CODE_ERROR, MSG_ERROR, list);
		try {
			list = informationService.selectInformationByCompanyId(null);
			return HttpUtils.formatData(format, CODE_OK, MSG_OK, list);
		} catch (Exception e) {
			LoggerUtils.fmtError(getClass(), "查询错误", e.getMessage());
			return HttpUtils.formatData(format, CODE_EXCEPTION, MSG_EXCEPTION, null);
		}
	}
}
